<template>
    <el-dialog v-model="show" title="采购入库" width="35%" align-center @close="handleClose">

        <el-row class="mb20">
            <el-col :span="12">
                品名规格：{{ props.purchaseRow.specsDetail || '' }}
            </el-col>
            <el-col :span="12">
                <el-row>
                    <el-col :span="12">
                        申请数量：{{ props.purchaseRow.number || 0 }}{{ getUnitLabel(props.purchaseRow.purchaseUnit) || '' }}
                    </el-col>
                    <el-col :span="12">
                        采购数量：{{ props.purchaseRow.purchaseNumber || 0 }}{{ getUnitLabel(props.purchaseRow.purchaseUnit)
                            || '' }}
                    </el-col>
                </el-row>
            </el-col>
        </el-row>
        <el-row class="mb20">
            <el-col :span="12">
                供应商：{{ props.purchaseRow.supplyFactoryName || '' }}
            </el-col>
            <el-col :span="12">
                已入库数量： {{ props.initList.alreadyNumber }}{{ getUnitLabel(props.initList.purchaseUnit) }} 计：
                {{ props.initList.actualNumber }}{{ getUnitLabel(props.purchaseRow.auxiliaryUnit) }}
            </el-col>
        </el-row>
        <el-row class="mb20">
            <el-col :span="12">
                采购备注：{{ props.purchaseRow.remark }}
            </el-col>
            <el-col :span="12">
                剩余到货数量：{{ props.initList.surplusNumber }}{{ getUnitLabel(props.initList.purchaseUnit) }} 计：{{
                    props.initList.actualSurplusNumber }}{{ getUnitLabel(props.purchaseRow.auxiliaryUnit) }}
            </el-col>
        </el-row>
        <el-row class="mb20">
            <el-col :span="24">
                审批备注：{{ props.purchaseRow.approvalRemark }}
            </el-col>
        </el-row>

        <el-divider />
        <div class="container">
            <div class="mb10"> <strong>入库信息</strong> </div>

            <div v-if="props.initList.dataList.length == 0">暂无入库信息</div>
            <div v-else>
                <div class="mb20" v-for="item in props.initList.dataList" :key="item.id">
                    <div>入库时间: {{ item.createTime }}</div>
                    <div>操作人: {{ item.updateByName }}</div>
                    <div>入库数量: {{ item.inNumber }}{{ getUnitLabel(item.inUnit) }} 计 {{ item.calNumber }}{{
                        getUnitLabel(item.calUnit) }}</div>
                </div>
            </div>
        </div>
        <el-divider />

        <el-row>
            <el-col :span="12" style=" display: flex; align-items: center;">
                本次到货数量：
                <el-input @input="handleInput" v-model="inNumber" :max="Number(props.initList.surplusNumber)"
                    type="number" :min="0" style="width: 150px;" placeholder="请输入">
                    <template #append>{{ getUnitLabel(props.initList.purchaseUnit) }}</template>
                </el-input>
            </el-col>
            <el-col :span="8" style="line-height: 30px;">
                计 {{ inNumber ? (Number(inNumber) / Number(props.initList.targetNumber)).toFixed(2) : 0 }} {{
                    getUnitLabel(props.purchaseRow.auxiliaryUnit) }}
            </el-col>
            <el-col :span="4">
                <el-checkbox v-model="purchaseOrderFinish" label="采购单完结" value="采购单完结" />
            </el-col>
        </el-row>

        <template #footer>
            <div class="dialog-footer">
                <el-button v-loading="loading" @click="handleClose">取 消</el-button>
                <el-button v-loading="loading" type="primary" @click="handleSubmit">确 定</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { addInboundOrdersApi } from '@/api/sj/purchaseManagement/toBeStored/index'

const { proxy } = getCurrentInstance() as any;
const props = defineProps(['visible', 'initList', 'purchaseRow']);
const emits = defineEmits(['submit', 'close']);
const { unit_enumeration } = toRefs(proxy?.useDict('unit_enumeration'));

const show = ref(false);
const loading = ref(false);

watch(() => props.visible, async (newValue) => {
    show.value = newValue
    if (newValue) {
        purchaseOrderFinish.value = false;
    }
}, { deep: true });

const inNumber = ref<number | null>(null); // 采购数量
const purchaseOrderFinish = ref(false);

// 监听 inputValue 变化，实时检查是否超过最大值
watch(inNumber, (newValue) => {
    if (newValue && newValue > Number(props.initList.surplusNumber)) {
        inNumber.value = Number(props.initList.surplusNumber); // 自动修正为最大值
    }

    if (newValue && newValue < 0) {
        inNumber.value = 0;
    }
});
// purchasePrice


const handleInput = (val: any) => {
    console.log(val);
};


const handleSubmit = async () => {

    if (!inNumber.value) return proxy?.$modal.msgError('请输入入库数量');
    loading.value = true;
    /**
     * 采购单完结 
     * 需要当前输入的入库数量 + 之前入库的数量 的总数
     * 和采购总数量相除 > 10% 提示  到货数量与申请采购数量相差较大，确认要完结此采购单么
     * 
     */

    if (purchaseOrderFinish.value && ((Number(inNumber.value) + Number(props.initList.alreadyNumber) / Number(props.purchaseRow.purchaseNumber))) > 0.1) {
        ElMessageBox.confirm('到货数量与申请采购数量相差较大，确认要完结此采购单么？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })
            .then(() => {
                postDaya()
            })
            .catch(() => {
                loading.value = false;
            });
    } else {
        postDaya()
    }
};

/** 提交数据 */
const postDaya = async () => {
    const params = {
        purchaseOrderId: props.purchaseRow.id,
        inNumber: inNumber.value,
        inUnit: props.initList.purchaseUnit,
        calNumber: Number(inNumber.value) / Number(props.initList.targetNumber),
        calUnit: props.purchaseRow.auxiliaryUnit || '1',
        inAmount: props.purchaseRow.purchasePrice,
        completeFlag: purchaseOrderFinish.value ? 1 : 0
    }

    try {
        const { code } = await addInboundOrdersApi(params);
        if (code == 200) {
            proxy?.$modal.msgSuccess('操作成功');
            loading.value = false;
            inNumber.value = NaN;
            purchaseOrderFinish.value = false;
            emits('submit', true);
            handleClose();
        }
    } catch (error) {
        loading.value = false;
        console.error('提交失败:', error);
        // proxy?.$modal.msgError('提交失败，请稍后再试');
    }
};

// 辅助函数获取单位标签
const getUnitLabel = (unitValue: string): string => {
    const unit = unit_enumeration.value?.find((item: any) => item.value === unitValue);
    return unit?.label || '';
};


const handleClose = () => {
    emits('close');
};

onMounted(() => {
})
</script>

<style lang="scss" scoped>
.container {
    color: #BDBDBD;
    height: 160px;
    overflow-y: auto;
}
</style>